/*
 * @Author: 卢景滔
 * @Date: 2021-06-21 10:17:12
 * @LastEditTime: 2021-06-21 15:27:00
 * @LastEditors: 卢景滔
 * @Description: mqtt 共享线程，主要用于多页面共享mqtt对象
 */

let mqttObj = null
let clients = []
let send = {}
let receive = {}
onconnect = (e) => {
  const port = e.ports[0]
  clients.push(port)
  console.log('已有数据：', mqttObj)
  console.log('clients', clients)

  port.onmessage = (re) => {
    receive = re.data
    console.log('mqtt-shared-worker接收到app数据', receive)
    if (receive.action === undefined) return
    switch (receive.action) {
      case 'getClientsCount':
        send = { action: 'setClientsCount', data: clients.length }
        console.log('mqtt-shared-worker向app发送数据', send)
        port.postMessage(send)
        break
      case 'getMqtt':
        if (mqttObj) {
          send = { action: 'setMqtt', data: mqttObj }
          console.log('mqtt-shared-worker向app发送数据', send)
          port.postMessage(send)
        } else {
          send = { action: 'noMqtt' }
          console.log('mqtt-shared-worker向app发送数据', send)
          port.postMessage(send)
        }
        break
      case 'setMqtt':
        console.log('mqtt-shared-worker存储数据', receive.data)
        mqttObj = receive.data
        break
      case 'deleteClient': // 删除单个客户端
        console.log('mqtt-shared-worker删除单个客户端')
        clients.pop()
        console.log('clients.length', clients.length)
        break
    }
  }
  // port.start()
}
